package com.dkd.model.base.utils;

import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

public  class ObjectToStringUtils {

	public static String ObjectToString(Object obj){
		StringBuffer sb = new StringBuffer();
		if(null != obj){
			boolean type = obj instanceof List || obj instanceof Map;
			//如果是集合
			if(type){
				sb.append(collection2String(obj));
			}else{
				sb.append(ReflectionToStringBuilder.toString(obj, ToStringStyle.SHORT_PREFIX_STYLE));
			}
		}
		return sb.toString();
	}

	private static String collection2String(Object obj){
		StringBuffer sb = new StringBuffer();
		if(obj instanceof List){
			List list = (List)obj;
			sb.append("{");
			for(Iterator it = list.iterator(); it.hasNext();){
				sb.append(ReflectionToStringBuilder.toString(it.next(), ToStringStyle.SHORT_PREFIX_STYLE));
			}
			sb.append("}");
		}else if(obj instanceof Map){
			Map map = (Map)obj;
			Iterator<Map.Entry> it = map.entrySet().iterator();
			sb.append("{");
			while (it.hasNext()) {
				Map.Entry entry = it.next();
				Object key = entry.getKey();
				Object value = entry.getValue();
				sb.append("[");
				if(key instanceof String){
					sb.append(key);
				}else{
					sb.append(ReflectionToStringBuilder.toString(key, ToStringStyle.SHORT_PREFIX_STYLE));
				}
				sb.append(":");
				if(value instanceof String){
					sb.append(value);
				}else{
					sb.append(ReflectionToStringBuilder.toString(key, ToStringStyle.SHORT_PREFIX_STYLE));
				}
				sb.append("]");
			}
			sb.append("}");
		}else{
			sb.append(ReflectionToStringBuilder.toString(obj, ToStringStyle.SHORT_PREFIX_STYLE));
		}
		return sb.toString();
	}

	/*
	public static void main(String[] args){
		List<ServiceCall> userList = new ArrayList<>();
		userList.add(new ServiceCall());
		userList.add(new ServiceCall());
		userList.add(new ServiceCall());
		userList.add(new ServiceCall());
		System.out.println(ObjectToStringUtils.ObjectToString(userList));
		Map<String, String> map = new HashMap<>();
		map.put("一", "一一一");
		map.put("二", "二二二");
		map.put("三", "三三三");
		System.out.println(ObjectToStringUtils.ObjectToString(map));
	}*/
}
